# -*- coding: utf-8 -*-
from datetime import datetime

from common.stats import MG_BIGBANG_COLL as mg
from common.utils.mg import parse_query, paginator
from common.utils.tz import local_now, utc_to_local_str
from common.utils.decorator import mongo_wrapper


@mongo_wrapper
def query_same_withdraw_user(withdraw_type, withdraw_no):
    return mg.withdraw_stats.find({'no': withdraw_no, 'type': int(withdraw_type)}).count()


@mongo_wrapper
def update_withdraw_stats(user_id, withdraw_type, withdraw_no, withdraw_amount):
    mg.withdraw_stats.update_one({
        'type': withdraw_type,
        'no': withdraw_no,
        'user_id': user_id
    },{'$set': {
        'last_ts': datetime.utcnow()
    },'$inc': {
        'count': 1,
        'amount': withdraw_amount
    },'$setOnInsert': {
        'created_at': datetime.utcnow()
    }}, upsert=True)


@mongo_wrapper
def list_withdraw_account(query_dct):
    query_cond = parse_query(query_dct)
    if 'user_id' in query_cond:
        query_cond['user_id'] = int(query_cond['user_id'])
    if 'type' in query_cond:
        query_cond['type'] = int(query_cond['type'])
    offset, size = paginator(query_dct)
    if '$orderby' in query_dct:
        sort_key = query_dct['$orderby']
        if sort_key.startswith('-'):
            sort_key = sort_key[1:]
            direction = -1
        else:
            direction = 1
        items = mg.withdraw_stats.find(query_cond).sort(sort_key, direction).skip(offset).limit(size)
    else:
        items = mg.withdraw_stats.find(query_cond).skip(offset).limit(size)
    total_count = mg.withdraw_stats.count(query_cond)
    return items, total_count
